//
//  SCLoginVC.m
//  Shuaiche
//
//  Created by zzs on 2017/11/1.
//  Copyright © 2017年 zzs. All rights reserved.
//

#import "SCLoginVC.h"
#import "NSString+Helper.h"
#import "SCNetworkStatusConst.h"
#import "SCHttpManager.h"
#import "MBProgressHUD+Add.h"
#import "SCConstants.h"
#import <JPUSHService.h>
#import "Config.h"
#import "User+CoreDataProperties.h"
#import "AppDelegate+Setup.h"
#import <MagicalRecord/MagicalRecord.h>
#import "SCNotificationMacro.h"
#import "CodeVerifyVC.h"
#import "SCFilterTextField.h"
#import "UIView+InputHandler.h"
#import "SCHelper.h"
#import "SCHttpManager.h"
#import "SCWebViewController.h"
#import <Masonry.h>
#import "SCDebugAccountsVc.h"
#import "AsyncTaskButton.h"
#import "SCRNEventManager.h"
#import "SCOneLoginTool.h"
#import "UserDefaultsUtils.h"

@interface SCLoginVC ()<CodeVerifyVCDelegate,UITextFieldDelegate,AsyncTaskCaptchaButtonDelegate>
@property (weak, nonatomic) IBOutlet SCFilterTextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *verificationCodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *verificationCodeBtn;
@property (weak, nonatomic) IBOutlet UIButton *signInBtn;
@property (strong, nonatomic) dispatch_source_t timerSource;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *verticalLayoutConstraint;
@property (weak, nonatomic) IBOutlet AsyncTaskButton *codeVerityButton;
@property (weak, nonatomic) CodeVerifyVC *codeView;
@property (weak, nonatomic) IBOutlet UIButton *checkBtn;
@property (copy, nonatomic) NSString *captchaKey;
@property (assign, nonatomic) BOOL captchaError;
- (IBAction)signInBtnClicked:(id)sender;
- (IBAction)verificationCodeBtnClicked:(id)sender;
- (IBAction)userNoticeBtnClicked:(id)sender;
- (IBAction)checkClick:(id)sender;

@end

@implementation SCLoginVC

- (instancetype)init{
    if(self = [super init]){
        [Config sharedConfig].isPresentedWhenSessionExpired = YES;
    }
    return self;
}

- (dispatch_source_t)timerSource{
    if(!_timerSource){
        WEAKSELF
        __block NSInteger count = 60;
        self.verificationCodeBtn.enabled = NO;
        dispatch_source_t timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
        dispatch_source_set_timer(timerSource, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0.001 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(timerSource, ^{
            STRONGSELF
            if(!strongSelf){
                Return_From_Block
            }
            [strongSelf.verificationCodeBtn setTitle:[NSString stringWithFormat:@"%@秒后重发",@(count)] forState:UIControlStateNormal];
            [strongSelf.verificationCodeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            count--;
            if(count==0){
                strongSelf.verificationCodeBtn.enabled = YES;
                [strongSelf.verificationCodeBtn setTitle:@"重发验证码" forState:UIControlStateNormal];
                [strongSelf.verificationCodeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                if(_timerSource){_timerSource = nil;}
            }
        });
        dispatch_resume(timerSource);
        _timerSource = timerSource;
    }
    return _timerSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"登录";
    if([[NSUserDefaults standardUserDefaults] objectForKey:kPhone]){
        self.phoneTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:kUsername];
    }
    self.phoneTextField.filterTextFieldType = SCFilterTextFieldPhoneNum;
    self.phoneTextField.scIntNumberOnly = YES;
    self.phoneTextField.delegate =self;
    self.verificationCodeTextField.scEmojiUnEnabled = YES;
    self.verificationCodeTextField.delegate = self;
    self.codeVerityButton.delegate = self;
    [self setupLeftBarButtonItem];

#ifndef APP_STORE

    UIView *debugGestureView = [[UIView alloc] init];
    [self.view addSubview:debugGestureView];
    [debugGestureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.view.mas_top).offset(108);
        make.width.height.equalTo(@90);
    }];
    UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(showDebugAccounts)];
    [debugGestureView addGestureRecognizer:press];
}

- (void)showDebugAccounts {
    SCDebugAccountsVc *acc = [[SCDebugAccountsVc alloc] init];
    [self presentViewController:acc animated:YES completion:nil];
    acc.selectBlock = ^(NSString * _Nonnull tel) {
        [self loginWithPhone:tel withCode:@"9999"];
    };
#endif
}

- (void)setupLeftBarButtonItem{
    if(self.isPresented){
        self.navigationItem.hidesBackButton = YES;
        self.navigationItem.leftBarButtonItem.tintColor = [UIColor clearColor];
        UIImage *backImage = [[UIImage imageNamed:@"back_icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
        self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    }
}

- (void)cancel{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [Config sharedConfig].isPresentedWhenSessionExpired = NO;
}

- (void)layoutSubviews{
    
}

- (void)setupSubViews{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    return [SCHelper customInputView:textField shouldChangeCharactersInRange:range replacementString:string];
}

#pragma -mark- 请求登录接口
- (void)loginWithPhone:(NSString *)phone withCode:(NSString *)code {
    [MBProgressHUD showMessage:@"正在登录..." toView:self.view];
    WEAKSELF
  NSMutableDictionary *param = [NSMutableDictionary dictionary];
  param[kPhone] = phone;
  param[kAuthorCode] = code;
  param[kSource] = @(15);
  NSDictionary *dic = [NSBundle mainBundle].infoDictionary;
  param[kVersion] = dic[@"CFBundleShortVersionString"];
  [[SCHttpManager shareInstance] httpPost:@"userprod/user/login" param:param completion:^(NSDictionary *response, NSError *error) {
    STRONGSELF
    if(!strongSelf){
        Return_From_Block
    }
    [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
    if (error) {
      [MBProgressHUD showError:error.localizedDescription toView:nil];
    } else {
      NSDictionary *data = response;
      NSNumber *sessionId = data[kSessionId];
      [[SCHttpManager shareInstance] updateHeaderFieldSession:sessionId];
      [[NSUserDefaults standardUserDefaults] setObject:sessionId forKey:kSessionId];
      [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsLogin];
      [[NSUserDefaults standardUserDefaults] setObject:phone forKey:kUsername];
      [[NSUserDefaults standardUserDefaults] setObject:data[kUserId] forKey:kUserId];
      [[NSUserDefaults standardUserDefaults] setObject:data[kMerchantId] forKey:kMerchantId];
      User *user = [User MR_findFirstOrCreateByAttribute:kUserId withValue:[[NSUserDefaults standardUserDefaults] objectForKey:kUserId]];
      user.phone = [NSString SC_trimString:phone];
      user.username = [NSString SC_trimString:phone];
      user.face  = data[kFace];
      user.fullname = data[kFullname];
      user.roleName = data[kRoleName];
      user.perms = [data[kPerms] integerValue];
      user.merchantName = data[kMerchantName];
      user.merchantAbbreviation = data[kMerchantAbbreviation];
      user.merchantId = [data[kMerchantId] intValue];
      user.merchantLogoPic = data[kMerchantLogoPic];
      user.imToken = data[kIMToken];
      user.imUserId = data[kIMUserId];
      user.imTokenExpireTimeSeconds = [data[kIMTokenExpireTimeSeconds] intValue];
      user.isFranchisee = data[kIsFranchisee] ? [data[kIsFranchisee] intValue]:0;
      //caicy 添加登录相关字段标识
      user.buyerId = data[kIsBuyerId] ? [data[kIsBuyerId] intValue]:0;
      user.isExternalCarEntryUser = data[kIsExternalCarEntryUser]? [data[kIsExternalCarEntryUser] intValue]:0;
      
      [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
      [Config fetchMaintenEnable];
      
      if (strongSelf.fromOtherLogin) {
        if (strongSelf.isPresented) {
          [strongSelf.viewController dismissViewControllerAnimated:NO completion:NULL];
        }else{
          [strongSelf.viewController.navigationController popViewControllerAnimated:NO];
        }
        [OneLogin dismissAuthViewController:NO completion:^{
          dispatch_async(dispatch_get_main_queue(), ^{
            self.loginSuccess();
          });
        }];
      }else{
        if(self.loginSuccess){
          self.loginSuccess();
        }
      }
      [JPUSHService setAlias:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:kUserId]] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        NSLog(@">>>setAlias:%zd,iAlias:%@",iResCode, iAlias);
      } seq:10];
      
      [[NSNotificationCenter defaultCenter] postNotificationName:SCNOTIFICATION_LOGIN_IN_OUT object:nil];
    }
}];
}

#pragma -mark- 登录按钮点击
- (IBAction)signInBtnClicked:(id)sender {
    [self.view endEditing:YES];
    if(![NSString SC_isValidatedPhone:self.phoneTextField.text]){
        [MBProgressHUD showError:SC_PHONE_INVALIDATED_MESSAGE toView:nil];
        return;
    }
    if(![NSString SC_isValidatedVerificationCode:self.verificationCodeTextField.text]){
        [MBProgressHUD showError:SC_VERIFICATION_CODE_INVALIDATED_MESSAGE toView:nil];
        return;
    }
    if (!_checkBtn.selected) {
        [MBProgressHUD showError:@"请选择同意用户协议" toView:nil];
        return;
    }
    [self loginWithPhone:[NSString SC_trimString:self.phoneTextField.text]  withCode:[NSString SC_trimString:self.verificationCodeTextField.text]];
}

#pragma -mark- 显示验证码视图
- (void)showCodeView{
    CodeVerifyVC *codeView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([CodeVerifyVC class]) owner:nil options:nil][0];
    codeView.autoresizingMask = UIViewAutoresizingNone;
    [codeView setFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:codeView];
    codeView.delegate = self;
    self.codeView = codeView;
}

- (UIImage *)dencode:(NSString *)base64String
{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
    UIImage *image = [UIImage imageWithData:data];
    return image;
}

#pragma -mark- 请求验证码刷新接口
- (void)refreshCode{
    WEAKSELF
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[kPhone] = self.phoneTextField.text;
  [[SCHttpManager shareInstance] httpGet:@"userprod/captcha/create" param:param completion:^(id response, NSError *error) {
      if([response[kCode] integerValue]==response_code_success){
          if(!response[kImageData]){
              weakSelf.codeView.codeImageView.image = [UIImage imageNamed:@"code_failed"];
              weakSelf.captchaKey = response[kCaptchaKey];
          }else{
              weakSelf.codeView.codeImageView.image = [weakSelf dencode:response[kImageData]];
              weakSelf.captchaKey = response[kCaptchaKey];
          }
      }else{
          weakSelf.codeView.codeImageView.image = [UIImage imageNamed:@"code_failed"];
          [MBProgressHUD showError:response[kMsg]?:response[kStatusText] toView:nil];
      }
  }];
}

#pragma -mark- 验证码点击
- (IBAction)verificationCodeBtnClicked:(id)sender {
    if(![NSString SC_isValidatedPhone:self.phoneTextField.text]){
        [MBProgressHUD showError:SC_PHONE_INVALIDATED_MESSAGE toView:nil];
        return;
    }
    if (self.captchaError) {
        [self showCodeView];
        [self refreshCode];
    }else{
        self.codeVerityButton.phoneStr = self.phoneTextField.text;
        [self.codeVerityButton startCaptcha];
    }
//    显示图形验证
//    [self showCodeView];
//    [self refreshCode];
}

#pragma -mark- 平台服务协议点击
- (IBAction)checkClick:(id)sender {
    _checkBtn.selected = !_checkBtn.selected;
}

- (IBAction)userNoticeBtnClicked:(id)sender {
  SCWebViewController *web = [[SCWebViewController alloc] init];
  web.urlPath = sc_url_web(kScServiceHtml);
  [self.navigationController pushViewController:web animated:YES];
}

#pragma -mark- 隐私协议点击
- (IBAction)privacyButtonClick:(UIButton *)sender {
  SCWebViewController *web = [[SCWebViewController alloc] init];
  web.urlPath = sc_url_web(kScPrivacyHtml);
  [self.navigationController pushViewController:web animated:YES];
}


#pragma mark -
#pragma mark - CodeVerifyVCDelegate
- (void)verifyCode:(NSString *)code{
    if(!self.captchaKey||[NSString SC_isBlankString:code]){
        [self refreshCode];
        //[MBProgressHUD showError:@"验证码不正确!" toView:nil];
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[kCaptchaKey] = self.captchaKey;
    param[kCaptchaValue] = code;
    param[kPhone] = [NSString SC_trimString:self.phoneTextField.text];
    param[kType] = @(1);
    [MBProgressHUD showMessage:Network_Request_Loading toView:self.view];
    WEAKSELF
  [[SCHttpManager shareInstance] httpPost:@"userprod/user/sendAuthorCode" param:param completion:^(id response, NSError *error){
    STRONGSELF
    if(!strongSelf){
        Return_From_Block
    }
    if (error) {
      strongSelf.verificationCodeBtn.enabled = YES;
      [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
      [MBProgressHUD showSuccess:@"验证码发送失败" toView:nil];
    } else {
      [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
      if([response[kCode] intValue]==response_code_success){
          (void)strongSelf.timerSource;
          [strongSelf closeVerifyView];
      }else if([response[kCode] integerValue]==response_code_verify_error){
          strongSelf.codeView.codeTextField.text = @"";
          [strongSelf refreshCode];
      }
      else{
          strongSelf.verificationCodeBtn.enabled = YES;
      }
      [MBProgressHUD showSuccess:SC_VERIFICATION_CODE_DISPATCHED toView:nil];
    }
  }];
}

- (void)closeVerifyView{
    [self.view endEditing:YES];
    if(self.codeView){
        [self.codeView removeFromSuperview];
    }
}

- (void)refreshCodeNumber{
    [self refreshCode];
}

#pragma mark - AsyncTaskCaptchaButtonDelegate

- (void)captchaWillDisplay {
//    [TipsView removeAllTipsView];
}

// 行为验证注册失败 使用原有的图形验证
- (void)captchaRegisterError{
    self.captchaError = YES;
}

- (BOOL)captchaButtonShouldBeginTapAction:(AsyncTaskButton *)button {
//    [TipsView showTipOnKeyWindow:@"正在检测\n智能账号安全..."];
    if(![NSString SC_isValidatedPhone:self.phoneTextField.text]){
        [MBProgressHUD showError:SC_PHONE_INVALIDATED_MESSAGE toView:nil];
        return NO;
    }
    return YES;
}

- (void)captchaDidFinish:(BOOL)status error:(GT3Error *)error {
    if (!error) {
        dispatch_async(dispatch_get_main_queue(), ^{
//            if ([self.phoneNumberTextField.text isEqualToString:@"12345678900"]) {
//                [TipsView showTipOnKeyWindow:@"DEMO: 已存在的手机号"];
//            }
//            else {
//                self.smsCodeTextField.text = @"88888888";
//                [TipsView showTipOnKeyWindow:@"DEMO: 获取短信验证码:88888888" fontSize:12];
//            }
            //行为验证通过 验证码倒计时开始
            (void)self.timerSource;
        });
    }
    else {
    }
}

- (void)dealloc{
    
    
}
@end
